# coding:utf-8
from __future__ import division
import argparse
import datetime
import os
import sys
import pysequoiadb
from pysequoiadb import client
from pysequoiadb.error import SDBBaseError,InvalidParameter
import pysequoiadb

flags = argparse.ArgumentParser()
flags.add_argument("--ip",type=str,required=True,help="addr of ip")
flags.add_argument("--dir",type=str,default="/data/log",help="dir of log")
flags.add_argument("--sdb_ip",type=str,help='ip of sdb')
args = flags.parse_args()

gpu_num=[0,1,2,3]
sdb_ip = args.sdb_ip
sdb_port = "11810"
sdb_user = "peter"
sdb_password = "Foxconn99."
collection_name = "gpucpu"
log_files = ["syscpu.log", "usercpu.log", "mem.log"]

# cl.create_index({"ip":1},"ipindex",True,True)
def get_gpu_or_mem(dir=args.dir,log_prefix=None):
    os.chdir(dir)
    norm_logs=[]
    # FIXME:正则
    for i in gpu_num:
        tmp_gpumem_log = log_prefix + str(i) + '.log'
        with open(tmp_gpumem_log,'r') as log:
            lines = log.readlines()
            if lines:
                infos = [float(line.strip('\n')) for line in lines]
                #平均值
                avg = float("%.1f" % (sum(infos) / len(infos)))
                norm_logs.append(avg)
            else:
                norm_logs.append(0.0)
    tmp = []
    for index,i in enumerate(norm_logs):
        tmp.append({str(index):i})
    return {log_prefix:tmp}


def get_norm_log(dir=args.dir):
    os.chdir(dir)
    norm_logs = {}
    for log_fi in log_files:
        tmp = log_fi.split(".")[0]
        with open(log_fi,'r') as log:
            lines = log.readlines()
            if lines:
                infos = [float(line.strip('\n')) for line in lines]
                avg = float("%.1f" % (sum(infos) / len(infos)))
                norm_logs[tmp] = avg
            else:
                norm_logs[tmp] = 0.0
    return norm_logs


def main():
    try:
        db = client(sdb_ip,sdb_port,sdb_user,sdb_password)
    except SDBBaseError as e:
        pysequoiadb._print(e)
        print("连接出错 请校验")
        sys.exit(0)
    cs = db.get_collection_space('face')
    try:
        cl = cs.get_collection(collection_name)
    except SDBBaseError as e:
        cl = cs.create_collection(collection_name,{'ShardingKey':{"_id":1},
                                                       'ShardingType':"hash",
                                                       'Partition':65536,
                                                       'ReplSize':1,
                                                       'Compressed':True,
                                                       'AutoSplit':True})


    gpumem = get_gpu_or_mem(log_prefix="gpumem")
    gpu = get_gpu_or_mem(log_prefix='nvidia_gpu')
    norm = get_norm_log()
    timezone = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    tip = {"ip":args.ip}
    # TODO:日期
    gpumem.update(gpu)
    gpumem.update(norm)
    gpumem.update({"time":timezone})
    tip.update(gpumem)

    try:
        cl.insert(tip)
    except InvalidParameter as e:
        print("插入出错")
        print(e.detail)


if __name__ == "__main__":
    main()